<template>
  <div ref="chart" style="height: 400px;"></div>
</template>

<script>
import * as echarts from 'echarts'
import { getGenderData } from '@/api/analysis'

export default {
  name: 'GenderChart',
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.loadData()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      this.chart.setOption({
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center'
        },
        series: [
          {
            name: '性别分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            }
          }
        ]
      })
    },
    async loadData() {
      try {
        const res = await getGenderData()
        const option = {
          series: [{
            data: [
              { value: res.data.maleCount, name: '男性' },
              { value: res.data.femaleCount, name: '女性' },
              { value: res.data.otherCount, name: '未知' }
            ]
          }]
        }
        this.chart.setOption(option)
        window.addEventListener('resize', this.resizeHandler)
      } catch (error) {
        console.error('加载性别数据失败:', error)
      }
    },
    resizeHandler() {
      this.chart.resize()
    }
  }
}
</script>
